package io.renren.modules.task.rabbitmq;

import io.renren.modules.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/9 13:28
 * @Version 1.0
 */
@Service
public class MQSender {

    @Autowired
    AmqpTemplate amqpTemplate;

    private static Logger logger = LoggerFactory.getLogger(MQReceiver.class);

    public void send(Object message){

        logger.info("rabbitMQ-- send message"+message);
        for (int i=0;i<3;i++){
            String msg = RedisService.beanToString(message);
            msg = msg +"|"+i;
            amqpTemplate.convertAndSend(MQConfig.QUEUE,msg);
        }
    }

    public void sendss(Object message){
        String msg = RedisService.beanToString(message);
        logger.info("rabbitMQ-- send message"+message);
        amqpTemplate.convertAndSend(MQConfig.QUEUESS,msg);
    }

    public void sendTopic(Object message){
        String msg = RedisService.beanToString(message);
        logger.info("send topic message -- send message"+message);
        //这里的生产者投递并不是，直接投递到消费者，而是投递到交换机，在交换机上通过路由匹配规则投递的对应的 队列上去。
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,"topic.key1",msg+"1");  //当我们这里发送消息了，Config中的 topicQueue1队列和topicQueue2队列都会收到消息
        amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE,"topic.key2",msg+"2");

    }

    public void sendFanout(Object message){
        String msg = RedisService.beanToString(message);
        logger.info("send fanout message -- send message"+message);
        amqpTemplate.convertAndSend(MQConfig.FANOUT_EXCHANGE,"",msg+"广播");  //因为是广播，所以两个队列都能收到

    }

    public void sendHeaders(Object message){
        String msg = RedisService.beanToString(message);
        logger.info("send headers message -- send message"+message);

        MessageProperties properties = new MessageProperties();
        properties.setHeader("header1","value1");
        properties.setHeader("header2","value2");
        Message obj = new Message(msg.getBytes(),properties);
        amqpTemplate.convertAndSend(MQConfig.HEADERS_EXCHANGE,"",obj);  //因为是广播，所以两个队列都能收到

    }
}
